<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? $t('sysManagement.add') : $t('sysManagement.modify')"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item
        label="版本号"
        prop="version"
      >
        <el-input
          v-model="dataForm.version"
          v-input-rule
          placeholder="版本号"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        label="更新日志"
        prop="updateLog"
      >
        <tiny-mce
          v-if="showTiny"
          ref="tinyMceRef"
          v-model="dataForm.updateLog"
          :tinymce-height="250"
        />
      </el-form-item>

      <el-form-item
        label="安装包"
        prop="docList"
      >
        <div class="upload-video-box">
          <div
            v-for="(item, index) in docList"
            :key="index"
            class="video-preview"
          >
            <div class="avatar-uploader-popup">
              <!-- <span style="padding:0 10px 0 3px">{{ item.name }}</span> -->
              <img src="@/assets/img/apk.png">
              <el-icon
                class="el-icon-delete"
                style="color: red"
                @click="preDeleteVideo(index)"
              >
                <Delete />
              </el-icon>
            </div>

            <!-- 显示上传进度 -->
            <div
              v-show="isSubmit"
              class="progress"
            >
              <el-progress
                type="circle"
                :width="80"
                :percentage="item.progress || 0"
              />
            </div>
          </div>
        </div>
        <el-upload
          v-show="docList.length == 0"
          ref="uploadRef"
          v-model:file-list="docList"
          name="excelFile"
          class="upload-img-preview"
          list-type="picture-card"
          action=""
          :multiple="false"
          :auto-upload="false"
          :show-file-list="false"
          :limit="1"
          :http-request="httpRequest"
          :on-change="onUploadChange"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('coupon.cancel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit(dataFormRef)"
        >
          {{ $t('coupon.confirm') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import http, { uploadFile } from '@/utils/http.js'
import TinyMce from '@/components/tiny-mce/index.vue'

const emit = defineEmits(['refreshDataList'])

const dataFormRef = ref(null)
const visible = ref(false)
const isSubmit = ref(false)
const dataForm = reactive({
  id: 0,
  version: '',
  updateLog: '',
  docList: []
})

const dataRule = {
  version: [
    { required: true, message: '版本不能为空', trigger: 'blur' }
  ],
  updateLog: [
    { required: true, message: '更新日志不能为空', trigger: 'blur' }
  ],
  docList: [
    { required: true, message: '安装包不能为空', trigger: 'blur' }
  ]
}

const showTiny = ref(false)
const init = (id) => {
  showTiny.value = false
  dataForm.id = id || 0
  visible.value = true
  isSubmit.value = false
  docList.value = []
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.id) {
      http({
        url: http.adornUrl(`/shop/pluginVersion/info/${dataForm.id}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.version = data.version
        dataForm.updateLog = data.updateLog
        docList.value = data.filePath ? [
          {
            filePath: data.filePath
          }
        ] : []
        dataForm.docList = docList.value.length
        showTiny.value = true
      })
    } else {
      showTiny.value = true
    }
  })
}
// 表单提交
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit.value) {
        return false
      }
      // 判断是否是新上传的文件
      const { status, filePath } = docList.value[0]
      if (status == 'success' && filePath) {
        onSave({
          id: dataForm.id || undefined,
          version: dataForm.version,
          updateLog: dataForm.updateLog,
          filePath
        })
        return
      }
      isSubmit.value = true
      uploadRef.value?.submit()
    }
  })
}

const onSave = (data) => {
  http({
    url: http.adornUrl('/shop/pluginVersion'),
    method: data.id ? 'put' : 'post',
    data: http.adornData(data)
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        isSubmit.value = false
        visible.value = false
        emit('refreshDataList')
      }
    })
  }).catch((e) => {
    isSubmit.value = false
    // docList.value = []
  })
}

const docList = ref([])
const uploadRef = ref(null)
const httpRequest = (event) => {
  docList.value.forEach(item => {
    if (item.uid === event.file.uid) {
      uploadFileDoc(event)
    }
  })
}

const uploadFileDoc = (event) => {
  const file = event.file
  http({
    url: http.adornUrl('/admin/file/getPreSignUrl'),
    method: 'get',
    params: http.adornParams({
      fileName: file.name,
      isImFile: false
    })
  }).then(async ({ data }) => {
    await uploadFile(data.preSignUrl, event.file, (evt) => {
      progressFn(event.file, evt)
    }).then(() => {
      // 文件太小 秒传 来不及调用progressFn 直接 100%
      progressFn(event.file, { loaded: 1, total: 1 })
      onSave({
        id: dataForm.id || undefined,
        version: dataForm.version,
        updateLog: dataForm.updateLog,
        filePath: data.filePath
      })
    })
  }).catch(() => {
    isSubmit.value = false
  })
}
const progressFn = (file, evt) => {
  docList.value.forEach(d => {
    if (d.uid === file.uid) {
      d.progress = parseInt(evt.loaded / evt.total * 100)
    }
  })
}

const onUploadChange = (file, fileList) => {
  const videoSrc = URL.createObjectURL(file.raw)
  docList.value.push({ url: videoSrc, uid: file.uid, name: file.name })
  dataForm.docList = docList.value.length
  dataFormRef.value?.validateField('docList')
}

const preDeleteVideo = (index) => {
  docList.value.splice(index, 1)
  dataForm.docList = docList.value.length || null
}

defineExpose({ init })
</script>

<style scoped lang="scss">
:deep(.el-form) {
  .el-form-item__label {
    word-wrap: break-word;
    word-break: break-word;
  }
}

.upload-video-box {
  width: 100%;

  .video-preview {
    width: 128px;
    height: 128px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    cursor: pointer;
    box-sizing: border-box;
    margin-right: 8px;
    margin-bottom: 5px;
    position: relative;
    overflow: hidden;

    &:hover{
      .el-icon-delete {
        display: block;
      }
    }

    .el-icon-delete{
      display: none;
      background: rgba(0, 0, 0, .3);
      height: 30px;
      width: 100%;
      text-align: center;
      padding: 5px;
      position: absolute;
      bottom: 0;
      left: 0;
      font-size: 20px;
    }

    .progress{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 128px;
      padding: 24px;
      background: rgba(0, 0, 0, .5);

      :deep(.el-progress__text){
        color: #fff;
      }
    }
  }
}
</style>
